package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.文章审核通过
    public void examine(String articleId){
        articleDao.examine(articleId);
    }
    //2.根据id查询文章
    public Article findById(String id){
        //1.从redis中查询文章
        Article article= (Article) redisTemplate.opsForValue().get("article_"+id);
        //2.如果不存在就从数据库中获取数据，并放到redis中
        if(article==null){
            //2.1调用dao层查询文章
            article = articleDao.findById(id).get();
            //2.2将文章放进redis中，并设置过期时间
            redisTemplate.opsForValue().set("article_"+id,article,100,TimeUnit.SECONDS);
            System.out.println("从数据库中获取数据！");
        }
        return article;
    }
    //3.修改文章
    public void update(Article article){
        //1.清理缓存
        redisTemplate.delete("article_"+article.getId());
        articleDao.save(article);
    }
    //4.删除文章
    public void delete(String id){
        //1.清理缓存
        redisTemplate.delete("article_"+id);
        articleDao.deleteById(id);
    }

}
